package com.frank.service.test3;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

import static com.frank.util.ByteBufferUtil.debugAll;

/**
 * @Author: huweifeng
 * @Date: 2024/12/11
 * @Description: 测试ByteBuffer与String的互转
 **/
public class TestByteBufferString {
    public static void main(String[] args) {
        // 1、字符串转为ByteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(16);
        buffer.put("hello".getBytes());
        debugAll(buffer);

        // 2、Charset，会自动切换到读模式
        ByteBuffer charsetBuffer = StandardCharsets.UTF_8.encode("hello");
        debugAll(charsetBuffer);

        // 3、wrap
        ByteBuffer wrapBuffer = ByteBuffer.wrap("hello".getBytes());
        debugAll(wrapBuffer);

        // 将buffer转为字符串
        String charsetStr = StandardCharsets.UTF_8.decode(charsetBuffer).toString();
        System.out.println("charsetStr = " + charsetStr);

        // 没有切换为读模式，就会为空字符串
        String bufferStr = StandardCharsets.UTF_8.decode(buffer).toString();
        System.out.println(bufferStr);
        buffer.flip(); // 切换为读模式
        String bufferStr2 = StandardCharsets.UTF_8.decode(buffer).toString();
        System.out.println(bufferStr2);
    }
}
